package com.eostoken.eos_wallet.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.AccountInfo;
import com.eostoken.eos_wallet.bean.TransferNameMode;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.eosnet.common.Params;
import com.eostoken.eos_wallet.eosnet.common.TransactionParams;
import com.eostoken.eos_wallet.helper.DialogConfirmListener;
import com.eostoken.eos_wallet.helper.DialogHelper;
import com.eostoken.eos_wallet.mvp.callback.CommonCallback;
import com.eostoken.eos_wallet.mvp.mode.TransactionModel;
import com.eostoken.eos_wallet.mvp.presenter.TransactionPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.TransactionView;
import com.eostoken.eos_wallet.ui.activity.QrcodeScanActivity;
import com.eostoken.eos_wallet.utils.CashierInputFilter;
import com.eostoken.eos_wallet.utils.ClipboardUtils;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.google.android.material.textfield.TextInputEditText;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eostoken.eos_wallet.utils.Constants.ACCOUNT_INFO;
import static com.eostoken.eos_wallet.utils.Constants.EOSIO_TOKEN_CONTRACT_CODE;
import static com.eostoken.eos_wallet.utils.Constants.INTENT_EXTRA_KEY_QR_SCAN;
import static com.eostoken.eos_wallet.utils.Constants.TO_TRANSFER_WALLET;
import static com.eostoken.eos_wallet.utils.Constants.TRANSFER_ACTION;

public class TransferFragment extends BaseFragment<TransactionModel, TransactionView, TransactionPresenterImpl> implements TransactionView {


    @BindView(R.id.topbar)
    QMUITopBarLayout topbar;
    @BindView(R.id.balanceTv)
    AppCompatTextView balanceTv;
    @BindView(R.id.layout)
    FrameLayout layout;
    @BindView(R.id.EOSAmountEt)
    TextInputEditText EOSAmountEt;
    @BindView(R.id.CollectionAddressTv)
    AppCompatTextView CollectionAddressTv;
    @BindView(R.id.CollectionAddressEt)
    TextInputEditText CollectionAddressEt;
    @BindView(R.id.memoTv)
    AppCompatTextView memoTv;
    @BindView(R.id.memoEt)
    TextInputEditText memoEt;
    @BindView(R.id.transactionBtn)
    QMUIRoundButton transactionBtn;

    private AccountInfo accountInfo;
    private String accountName;
    private String balance = "0";
    private String privatekey;
    private String jsonData;
    private MgpWallet wallet;
    private QMUIDialog qmuiDialog;
    private String to;
    private String scanResult;

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_transfer_eos;
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        accountName = WalletUtils.getCurrentAccountName();
        scanResult = bundle.getString(INTENT_EXTRA_KEY_QR_SCAN, "");
        if (!ObjectUtils.isEmpty(scanResult)) {
            TransferNameMode transferNameMode = GsonUtils.fromJson(scanResult, TransferNameMode.class);
            to = transferNameMode.getAccountName();
            CollectionAddressEt.setText(to);
        }
        presenter.requestAccountInfo(Params.getAccountPamars(accountName));
        privatekey = WalletUtils.getCurrentPrivatekey();
        WalletUtils.queryWallet(getActivity(), accountName, new CommonCallback() {
            @Override
            public void onSuccess(Object data, String successMsg, int responseSuccessCode) {
                List<MgpWallet> walletList = (List<MgpWallet>) data;
                wallet = walletList.get(0);
            }

            @Override
            public void onFailure(String msg, int responseFailCode) {
            }
        });
    }

    @Override
    protected void initView(View contentView) {
        topbar.setTitle(StringUtils.getString(R.string.str_mgp_transfer));
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });
        topbar.addRightImageButton(R.mipmap.qrcode_icon_2, R.id.topbar_right_change_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        balanceTv.setText(String.format(StringUtils.getString(R.string.str_balance), balance));
        InputFilter[] filters = {new CashierInputFilter()};
        EOSAmountEt.setFilters(filters);
    }

    /**
     * 开始扫码
     */
    public void startQrCode() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(UtilsTransActivity activity, ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(getActivity(), shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        Intent intent = new Intent(getActivity(), QrcodeScanActivity.class);
                        startActivityForResult(intent, Constants.REQUEST_SCAN_CODE);
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {

                    }
                }).request();
    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {
        LogUtils.dTag(Constants.TAG_MGP, "TransferFragment = " + o1);
        if (ObjectUtils.equals(ACCOUNT_INFO, o2)) {
            if (success) {
                accountInfo = (AccountInfo) o1;
                balance = accountInfo.getCore_liquid_balance();
                if (ObjectUtils.isEmpty(balance)) {
                    balance = "0 MGP";
                }
                balanceTv.setText(String.format(StringUtils.getString(R.string.str_balance), balance));
            } else {
                ToastUtils.showShort(R.string.str_get_balance_fail);
            }
        } else {
            if (success) {
                ToastUtils.showShort(R.string.str_transaction_success);
                popOrFinish();
            } else {
                ToastUtils.showShort(o1.toString());
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.REQUEST_SCAN_CODE:
                if (!ObjectUtils.isEmpty(data)) {
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString(Constants.INTENT_EXTRA_KEY_QR_SCAN);
                    if (!ObjectUtils.isEmpty(scanResult)) {
                        if (scanResult.contains("\"type\":\"" + TO_TRANSFER_WALLET + "\"") || scanResult.contains("\"type\":" + TO_TRANSFER_WALLET)) {
                            TransferNameMode transferNameMode = GsonUtils.fromJson(scanResult, TransferNameMode.class);
                            to = transferNameMode.getAccountName();
                        } else {
                            if (scanResult.getBytes().length != 12) {
                                to = "";
                                ToastUtils.showShort(R.string.str_illegal_account);
                                DialogHelper.showLongMessageDialog(getActivity(), getString(R.string.str_prompt_message), scanResult, getString(android.R.string.cancel), getString(R.string.str_copy), new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        dialog.dismiss();
                                    }
                                }, new QMUIDialogAction.ActionListener() {
                                    @Override
                                    public void onClick(QMUIDialog dialog, int index) {
                                        ClipboardUtils.copyText(scanResult);
                                        ToastUtils.showShort(StringUtils.getString(R.string.str_copy_success));
                                        dialog.dismiss();
                                    }
                                }).show();
                            } else {
                                to = scanResult;
                            }
                        }
                        CollectionAddressEt.setText(to);
                    }
                }
                break;
            default:
        }
    }

    @OnClick(R.id.transactionBtn)
    public void onViewClicked() {
//        "{\n" +
//                "\"from\": \"" + fromAccount + "\",\n" +
//                "\"to\": \"" + toAccount + "\",\n" +
//                "\"quantity\": \"" + amount + "\",\n" +
//                "\"memo\" : \"" + memo + "\"\n" +
//                "}";

        String quantity = EOSAmountEt.getText().toString().trim();
        to = CollectionAddressEt.getText().toString().trim();
        if (ObjectUtils.isEmpty(quantity) || ObjectUtils.isEmpty(to)) {
            ToastUtils.showLong(R.string.str_cannot_empty);
            return;
        }
        BigDecimal bdQuantity = new BigDecimal(quantity);
        String[] arr = balance.split(" ");
        BigDecimal bdBalance = new BigDecimal(arr[0]);

        if (bdQuantity.compareTo(bdBalance) == 1) {
            ToastUtils.showLong(R.string.str_cannot_greater_balance);
            return;
        }

        quantity = bdQuantity.setScale(4, BigDecimal.ROUND_HALF_DOWN).toPlainString();

        String memo = memoEt.getText().toString().trim();
        TransactionParams transactionParams = new TransactionParams();
        transactionParams.setMemo(memo);
        transactionParams.setQuantity(String.format(StringUtils.getString(R.string.str_balance_unit_blank), quantity));
        transactionParams.setTo(to);
        transactionParams.setFrom(accountName);

        jsonData = GsonUtils.toJson(transactionParams);
        if (qmuiDialog == null) {
            qmuiDialog = DialogHelper.showEditTextDialog(getActivity(), getString(R.string.str_password_authentification),
                    getString(R.string.str_enter_password), getString(android.R.string.ok), getString(android.R.string.cancel), listener, true);
        }
        qmuiDialog.show();
    }

    private void clearEditText() {
        EOSAmountEt.setText("");
        memoEt.setText("");
        CollectionAddressEt.setText("");
    }

    DialogConfirmListener listener = new DialogConfirmListener() {
        @Override
        public void onClick(QMUIDialog dialog, View view, int index) {
            dialog.dismiss();
            EditText editText = (EditText) view;
            String contrastPassword = editText.getText().toString().trim();
            if (ObjectUtils.equals(contrastPassword, wallet.getWalletPassword())) {
                transferTransaction();
            } else {
                ToastUtils.showShort(StringUtils.getString(R.string.str_wrong_password));
            }
            editText.setText("");
        }
    };


    private void transferTransaction() {
        LogUtils.dTag(Constants.TAG_MGP, " privatekey = " + privatekey
                + "accountName = " + accountName
                + "params = " + jsonData);
        presenter.sendTransaction(TRANSFER_ACTION, privatekey, accountName, EOSIO_TOKEN_CONTRACT_CODE, jsonData);
        jsonData = "";
    }

    @Override
    public TransactionModel createModel() {
        return new TransactionModel();
    }

    @Override
    public TransactionView createView() {
        return this;
    }

    @Override
    public TransactionPresenterImpl createPresenter() {
        return new TransactionPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void onStop() {
        super.onStop();
        clearEditText();
    }
}
